# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.pipelines.images import ImagesPipeline
from scrapy import Request
from scrapy.exceptions import DropItem


class ImagePipeline:
    def process_item(self, item, spider):
        return item


class ImageFilePipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        if item:
            if 'image_urls' in item and item["image_urls"]:
                yield Request(item["image_urls"], meta={'item': item})

    def file_path(self, request, response=None, info=None, *, item=None):
        """
        处理对象:每张图片
        返回的path是item中每一张图片的路径
        """
        item = request.meta["item"]
        if item['imgAlt'] != item['title']:
            image_name = item['title'].split('(')
            dir_name = image_name[0]
            file_name = image_name[1].split('/')[0].strip(')')
            path = dir_name + '/' + file_name + '.jpg'
        else:
            dir_name = item['title']
            file_name = item["image_urls"].split('/')[-1].split('.')[0]
            path = dir_name + '/' + file_name + '.jpg'
        return path

    def item_completed(self, results, item, info):
        """
        处理对象:每组item中的图片
        """
        image_path = [x['path'] for ok, x in results if ok]
        if not image_path:
            raise DropItem('Item contains no images')
        item['imgPath'] = image_path
        return item
